
package im

import (
    "time"
	"encoding/json"
	"strconv"
    "dhfshop/controllers/base"
	"dhfshop/utils/response"
	"dhfshop/models/im"
	"dhfshop/service/wscom"
	"github.com/astaxie/beego"
	//"github.com/gorilla/websocket"
)

type WebSocketController struct {
	base.BaseController
}

func (this *WebSocketController) Join() {
	//curRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	if curUserId == 0 {
		this.ServeError("user is not login")
	    return
	}
	client := this.GetString("client")
	if client == "" {
	    //this.ServeError("client is null")
	    //return
		client = "phone"
	}
	connectSvr := wscom.NewConnectSvr()
	code, err := connectSvr.Connect(this.Ctx.ResponseWriter, this.Ctx.Request, client, int(curUserId))
	if code == 0 && err == nil {
		time.AfterFunc(5*time.Second, func() {
			if records, err := im.GetUnreadMessage(partnerId); err == nil {
				if len(records) > 0 {
					latestRecord := records[0]
					req := im.NewRequestDao()
					req.Cmd = "receive"
					req.AppId = latestRecord.AppId
					req.MemberOpenId = latestRecord.MemberOpenId
					req.AgentOpenId = latestRecord.AgentOpenId
					req.MsgId = strconv.FormatInt(latestRecord.ChatRecordId, 10)
					req.UnreadCount = len(records)
					req.CreateTime = latestRecord.MsgTime.Unix()
					message, _ := json.Marshal(req)
					requestSrv := wscom.NewRequestSrv()
					token := client + "_" + strconv.FormatInt(curUserId, 10)
					if c, err := wscom.ConnectHub.GetConnectSvr(token); err == nil {
						requestSrv.ParserMsg(c, message)
						//beego.Debug("Join requestSrv.Parser func:")
					}
					//beego.Debug("Join getUnreadMessage:",latestRecord.AppId,latestRecord.AgentOpenId,latestRecord.ChatRecordId)
				}
			}
		})
		connectSvr.Reader(curUserId)
	} else {
		beego.Error("info:" + response.LangConf.Get(strconv.Itoa(code)).MustString())
		this.ServeError(response.LangConf.Get(strconv.Itoa(code)).MustString())
		return
	}
}


